<?php

namespace frontend\controllers;

use backend\models\GrpClass;
use backend\models\GrpKuaidi;
use backend\models\PayRebateUsertake;
use backend\models\PayScoreItem;
use backend\models\PayTradeRebate;
use backend\models\PrfConfig;
use backend\models\PrfCoupon;
use backend\models\PrfScoreExchange;
use backend\models\UserMessage;
use backend\models\UserPayVip;
use frontend\models\PayLogistics;
use frontend\models\PayTradeDel;
use frontend\models\SendSms;
use frontend\models\SysItem;
use frontend\models\UserCoupon;
use frontend\views\account\CouponModule;
use Yii;
use yii\db\Query;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\helpers\Url;
use frontend\models\UserInfo;
use frontend\models\UserInfoEx;
use frontend\models\User;
use backend\models\PrfType;
use backend\models\Image;
use frontend\views\account\FavouriteModule;
use frontend\models\AddressForm;
use frontend\models\UserAddress;
use frontend\models\UserShoppingCart;
use yii\db\ActiveRecord;
use yii\data\Pagination;
use frontend\models\PayTrade;
use frontend\models\UserFavourite;
use frontend\models\TaoZhuang;
use backend\models\SysUserDesigner;
use frontend\models\GrpCity;
use yii\web\UploadedFile;
use frontend\models\LogPay;
use backend\models\UserInvite;
use frontend\models\LogUserFootprint;
use frontend\models\modifyPassword;
use frontend\models\UserSignMonth;
use frontend\models\UserSignContinuity;
use backend\models\LogUserScore;
use yii\widgets\LinkPager;

class AccountController extends Controller
{
    public $sidebarStr = '<div class="sidebar col-md-3 col-sm-3">
                    <ul class="list-group margin-bottom-25 sidebar-menu">
                      <li class="list-group-item clearfix"><a href="my-shopping-car"><i class="fa fa-angle-right"></i> 我的购物车</a></li>
                      <li class="list-group-item clearfix"><a href="order-list"><i class="fa fa-angle-right"></i> 我的订单</a></li>
                      <li class="list-group-item clearfix"><a href="invited-friend"><i class="fa fa-angle-right"></i> 我邀请的朋友</a></li>
                      <li class="list-group-item clearfix"><a href="my-sign-in"><i class="fa fa-angle-right"></i>每日签到</a></li>
                      <li class="list-group-item clearfix"><a href="my-coupon"><i class="fa fa-angle-right"></i> 我的优惠券</a></li>
                      <li class="list-group-item clearfix"><a href="my-favourite"><i class="fa fa-angle-right"></i> 我的收藏</a></li>
                      <li class="list-group-item clearfix"><a href="my-coin"><i class="fa fa-angle-right"></i> 我的金币</a></li>
                      <li class="list-group-item clearfix"><a href="my-foot"><i class="fa fa-angle-right"></i>我的足迹</a></li>
                      <li class="list-group-item clearfix"><a href="my-reward"><i class="fa fa-angle-right"></i>我的奖励</a></li>
                      <li class="list-group-item clearfix"><a href="apply-designer"><i class="fa fa-angle-right"></i> 申请VIP会员</a></li>
                      <li class="list-group-item clearfix"><a href="apply-super-designer"><i class="fa fa-angle-right"></i> 申请超级设计师</a></li>
                      <li class="list-group-item clearfix"><a href="my-message"><i class="fa fa-angle-right"></i> 我的消息</a></li>
                      <li class="list-group-item clearfix"><a href="my-account"><i class="fa fa-angle-right"></i> 我的账户</a></li>
                      <li class="list-group-item clearfix"><a href="my-address"><i class="fa fa-angle-right"></i> 我的地址</a></li>
                  <!--<li class="list-group-item clearfix"><a href="my-show-home"><i class="fa fa-angle-right"></i> 我的秀家</a></li>-->
                  <!--<li class="list-group-item clearfix"><a href="reset-password"><i class="fa fa-angle-right"></i> 重设密码</a></li>-->
                      <li class="list-group-item clearfix"><a href="modify-password"><i class="fa fa-angle-right"></i> 修改密码</a></li>
                    </ul>
                    </div>';
    public $cart_map = [
        '0' => 1,
        '1' => 2,
        '2' => 3,
        '3' => 4,
        'singleItem' => 1,
        'tz' => 2,
        'GJJPackage' => 3,
        'diy'=>1
    ];
    public $coupon_type=[
        '0'=>'item',
        '1'=>'set',
        '2'=>'item',
        '3'=>'item',
        'singleItem'=>'item',
        'tz'=>'set',
        'GJJPackage'=>'item',
        'diy'=>'item'
    ];

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [
                            'my-account', 'my-address', 'my-shopping-car',
                            'my-favourite', 'my-foot', 'my-show-home', 'reset-password',
                            'edit-account-info', 'shoppingcart-del', 'delete-foot', 'tz', 'show',
                            'delete-from-cart', 'upload-avatar', 'add-address', 'add-favourite',
                            'remove-favourite','invited-friend', 'submit-cart', 'submit-order',
                            'submit-result',
                            'order-list', 'order-operate', 'apply-designer', 'modify-password',
                            'test', 'order-refund-apply', 'order-logistics-query', 'my-coupon',
                            'get-coupon', 'my-coin', 'exchange-list', 'exchange','my-reward',
                            'my-sign-in','sign-in','my-message','msg-read','apply-super-designer'
                        ],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['city', 'submit-success'],
                        'allow' => true,
                        'roles' => ['?', '@'],
                    ]
                ],
            ]
        ];
    }

    public function actionTest()
    {
        $this->test2();
    }
    private function test2()
    {
        $this->redirect(['www.baidu.com'], 'http');
    }
    //申请超级设计师
    public function actionApplySuperDesigner()
    {
        if (!Yii::$app->getUser()->isGuest) {
            $uid = Yii::$app->getUser()->identity->getId();
            $ret = array();

            //判断是否是VIP会员
            $isDesigner = SysUserDesigner::find()->where(['uid' => $uid, 'audit_state' => 1])->exists();
            if (!$isDesigner) {
                return $this->render('submitSuccess', [
                    'redirectUrl' => Url::to(['account/apply-designer']),
                    'status' => 'warning',
                    'msg' => '您需要先申请成为VIP会员',
                ]);
            }

            //判断是否是超级设计师
            $super = UserPayVip::find()->where(['user_id' => $uid])->andWhere(['>', 'end_time', time()])->one();
            if (!empty($super)) {
                $ret['status'] = 1;
                $ret['msg'] = ' 您已经是超级设计师。';

                //最后一个月提示续费
                if ($super->end_time - time() < 2592000 && $super->end_time - time() > 0) {
                    $ret['status'] = 2;
                    $ret['msg'] = ' 您已经是超级设计师，一个月内即将过期。';
                }

                $ret['deadline'] = '有效期 '.date('Y-m-d', $super->start_time).' 到 '.date('Y-m-d', $super->end_time);
            } else {
                $ret['status'] = 0;
                $ret['msg'] = '您还不是VIP会员';
            }

            return $this->render('applySuperDesigner', [
                'sidebar' => $this->sidebarStr,
                'ret' => $ret,
            ]);
        } else {
            return $this->redirect(['site/login']);
        }

    }

    //我的消息
    public function actionMyMessage()
    {
        if (!Yii::$app->user->isGuest) {
            $uid = Yii::$app->user->identity->getId();
            $pageSize = 6;

            $model = UserMessage::find()->joinWith(['msg0.iconImg0'])->where(['uid' => $uid]);


            $count = $model->count();

            $pagination = new Pagination([
                'defaultPageSize' => $pageSize,
                'totalCount' => $count
            ]);

            $data = $model->orderBy(['create_time' => SORT_DESC])->offset($pagination->offset)->limit($pagination->limit)->asArray()->all();

            return $this->render('myMessage', [
                'sidebar' => $this->sidebarStr,
                'data' => $data,
                'pagination' => $pagination,
            ]);
        } else {
            return $this->redirect(Url::to['site/login']);
        }
    }
    //消息已读
    public function actionMsgRead()
    {
        if (Yii::$app->request->isAjax) {
            $msgid = Yii::$app->request->post('msgid');
            $uid = Yii::$app->user->identity->getId();

            UserMessage::updateAll(['read' => 1], ['msgid' => $msgid, 'uid' => $uid]);
        }
    }

    //签到页面
    public function actionMySignIn()
    {
        //后台数据记录
        if (!Yii::$app->user->isGuest) {
            $uid = Yii::$app->user->identity->id;
            //这个月一号的时时间戳
            $thisMon = strtotime(date('Y-m-01', time()));
            $isCreateThisMon = UserSignMonth::find()->where(['uid' => $uid, 'time_month' => $thisMon])->exists();
            $data = array();
            if (!$isCreateThisMon) {
                $model = new UserSignMonth();
                $model->uid = $uid;
                $model->time_month = $thisMon;
                $model->all_day = date('t', time());
                $monStr = [];
                for ($i = 0, $len = $model->all_day; $i < $len; $i++) {
                    $monStr[$i] = 0;
                }
                $model->day_sign = implode(',', $monStr);
                if ($model->save()) {
                    $data['daySign'] = $model->day_sign;
                    $data['mon'] = date('Y年m月', time());
                    $userSignContity = UserSignContinuity::findOne(['uid' => $uid]);
                    $data['count'] = (!empty($userSignContity) && (time() - $userSignContity->sign_time < 172800))? $userSignContity->continuity_count : 0;
                    $score = LogUserScore::find()->where(['uid' => $uid])->sum('score');
                    $data['score'] = !empty($score) ? $score : 0;
                    $data['time'] = time();
                } else {
                    exit('创建当月失败');
                }
            }
            else {
                $model = UserSignMonth::findOne(['uid' => $uid, 'time_month' => $thisMon]);
                $data['daySign'] = $model->day_sign;
                $data['mon'] = date('Y年m月');
                $userSignContity = UserSignContinuity::findOne(['uid' => $uid]);
                $data['count'] = (!empty($userSignContity) && (time() - $userSignContity->sign_time < 172800))? $userSignContity->continuity_count : 0;
                $data['score'] = LogUserScore::find()->where(['uid' => $uid])->sum('score');
                $data['time'] = time();
            }
            return $this->render('mySignin', [
                'data' => $data,
                'sidebar' => $this->sidebarStr
            ]);
        } else {
            $this->redirect(['site/login']);
            return;
        }
    }

    //点击签到
    public function actionSignIn()
    {
        if (Yii::$app->request->isAjax) {
            $uid = Yii::$app->user->identity->id;

            $thisDayZore = strtotime(date('Y-m-d', time()));

            $ret = array();

            $isCreateContinuity = UserSignContinuity::find()->where(['uid' => $uid])->exists();
            if ($isCreateContinuity) {
                $userSign = UserSignContinuity::findOne(['uid' => $uid]);
                //判断今天是否签过
                $passTime = time() - $userSign->sign_time;
                if ($passTime < 86400) {
                    $ret['status'] = -1;
                    $ret['msg'] = '不能重复签到';
                    return json_encode($ret, JSON_UNESCAPED_UNICODE);
                }
                //判断是不是第二天签到
                $userSign->continuity_count = $passTime < 172800 ? $userSign->continuity_count + 1 : 1;
            } else {
                $userSign = new UserSignContinuity();
                $userSign->uid = $uid;
                $userSign->continuity_count = 1;
            }
            $userSign->sign_time = $thisDayZore;

            if (!$userSign->save()){
                $ret['status'] = -1;
                $ret['msg'] = '写入连续签到记录表失败';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            //更改daysign
            $thisMon = strtotime(date('Y-m-01', time()));
            $change_day_sign = UserSignMonth::findOne(['time_month' => $thisMon, 'uid' => $uid]);
            $daySign = explode(',',$change_day_sign->day_sign);
            $thisDay = intval(date('d', time()));
            $daySign[$thisDay-1] = 1;
            $change_day_sign->day_sign = implode(',', $daySign);

            if (!$change_day_sign->save()) {
                $ret['status'] = -1;
                $ret['msg'] = '更改daysign字段失败';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            //签到计入分数表
            $dayScore = PrfConfig::findOne(['config_attribute' => 'sign_point'])->config_value;
            $weekScore = PrfConfig::findOne(['config_attribute' => 'sign_week_point'])->config_value;
            $monScore = PrfConfig::findOne(['config_attribute' => 'sign_month_point'])->config_value;

            $logUserScore = new LogUserScore();
            $logUserScore->uid = $uid;
            if ($userSign->continuity_count < 7) {
                $logUserScore->score = $dayScore;
            } elseif ($userSign->continuity_count < 30) {
                $logUserScore->score = $weekScore;
            } else {
                $logUserScore->score = $monScore;
            }
            $logUserScore->score_key = date('Y-m-d', time());
            $logUserScore->time = time();
            $logUserScore->state = 2;
            $logUserScore->memo = "签到 {$userSign->continuity_count} 天";

            if ($logUserScore->save()) {
                $ret['status'] = 1;
                $ret['msg'] = '签到成功';
            } else {
                $ret['status'] = -1;
                $ret['msg'] = '写入用户计分表失败';
            }
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
    }

    public function actionMyReward()
    {
        $uid = Yii::$app->user->identity->id;
        $pageSize = 10;

        $query1 = PayRebateUsertake::find()->select(['uid', 'tm' => 'take_time', 'at' => 'take_money', 'ty' => 'CONCAT(-5)'])->where(['uid' => $uid])->andWhere('state != 3')->orderBy(['take_time' => SORT_DESC]);
        $query2 = PayTradeRebate::find()->select(['uid', 'tm' => 'create_time', 'at' => 'rebate_money', 'ty' => 'level'])->where(['uid' => $uid])->andWhere('state != 2')->orderBy(['create_time' => SORT_DESC]);

        $count = (new Query())->from(['num' => $query1->union($query2)])->count();

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);

        $alluser_take = PayTradeRebate::find()->where("uid = $uid AND state != 2")->sum('rebate_money');

        $take_money = PayRebateUsertake::find()->where("uid = $uid AND  state != 3")->sum('take_money');

        $available = $alluser_take -  $take_money ;

        $query3 = PayRebateUsertake::find()->select(['uid', 'tm' => 'take_time', 'apply_t' => 'apply_time', 'ok_t' => 'ok_time', 'err_t' => 'err_time', 'at' => 'take_money', 'ty' => 'CONCAT(-5)', 'no' => 'CONCAT("")', 'st' => 'state'])->where("uid = $uid AND state != 3")->orderBy(['apply_time' => SORT_DESC]);
        $query4 = PayTradeRebate::find()->select(['uid', 'tm' => 'create_time', 'apply_t' => 'create_time', 'ok_t' => 'CONCAT(-1)', 'err_t' => 'CONCAT(-1)', 'at' => 'rebate_money', 'ty' => 'level', 'no' => 'trade_no', 'st' => 'state'])->where("uid = $uid AND state != 2")->orderBy(['create_time' => SORT_DESC]);

        $rebate = (new Query())->select('tab.uid , tab.tm , tab.at , tab.ty , tab.no , tab.st , tab.apply_t , tab.ok_t , tab.err_t')->from(['tab' => $query3->union($query4)])->orderBy(['tab.apply_t' => SORT_DESC])->offset($pagination->offset)->limit($pagination->limit)->all() ;

        return $this->render('myReward',[
            'sidebar' => $this->sidebarStr,
            'rebate' => $rebate,
            'pagination' => $pagination,
            'available' => $available,
            'take_money' => $take_money,
        ]);
    }

    //我的金币
    public function actionMyCoin()
    {
        $pageSize = 10;
        $uid = Yii::$app->user->identity->id;

        $userScore = LogUserScore::find()->where(['uid' => $uid])->orderBy(['time' => SORT_DESC]);
        $count = $userScore->count();

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $coinList = $userScore->offset($pagination->offset)->limit($pagination->limit)->asArray()->all();
        $score = $userScore->sum('score');

        return $this->render('myCoin', [
            'sidebar' => $this->sidebarStr,
            'pagination' => $pagination,
            'data' => $coinList,
            'score' => $score
        ]);
    }

    //积分兑换页
    public function actionExchangeList()
    {
        $user_id = Yii::$app->user->identity->id;
        $pageSize = 8;
        $nowTime = time();

        $scoreExchange = PrfScoreExchange::find()->where(['or', ['<', 'start_time', $nowTime], ['start_time' => 0]])->andWhere(['or', ['>', 'end_time', $nowTime], ['end_time' => 0]]);
        $count = $scoreExchange->count();

        $paginationExchange = new Pagination([
            "defaultPageSize" => $pageSize,
            "totalCount" => $count
        ]);

        $getExchange = $scoreExchange->with(['img0', 'item0'])->offset($paginationExchange->offset)->limit($paginationExchange->limit)->asArray()->all();

        $str = '';
        foreach ($getExchange as $value) {
            if ($value['start_time'] == 0 && $value['end_time'] == 0) {
                $showTime = '不限';
            } elseif ($value['start_time'] > 0 && $value['end_time'] == 0) {
                $showTime = date('Y-m-d', $value['start_time']) . ' 起';
            } elseif ($value['start_time'] == 0 && $value['end_time'] > 0) {
                $showTime = date('Y-m-d', $value['end_time']) . ' 止';
            } else {
                $showTime = date('Y-m-d', $value['start_time']) . '-' . date('Y-m-d', $value['end_time']);
            }
            $wethershipping = ['0' => '到付', '1' => '包邮'];
            $str .= '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 item_one">
                      <div class="exchange-item">
                          <div class="pi-img-wrapper" >
                              <span class="newspan"></span>
                              <img src="' . Yii::$app->params['imgPath0'] . $value['img0']['url'] . '" class="img-responsive">
                          </div>
                          <h4 class="item_name">
                              <a href="javascript:;">' . $value['item0']['name'] . '
                                <span class="logistics-box">' . $wethershipping[$value['freeShipping']] . '</span>
                              </a>
                          </h4>
                          <div class="fav-info">
                              <span class="pull-left">' . $value['title'] . '</span>
                              <span class="pull-right cash">' . $value['item0']['price_base'] . '</span>
                          </div>
                          <div class="fav-info">
                              <span class="pull-left">剩余' . $value['last_total'] . '件</span>
                              <span class="pull-left">&nbsp;&nbsp;兑换金币' . $value['integral'] . '</span>
                              <a class="pull-right exchange" data-id="' . $value['id'] . '" href="javascript:;">兑换</a>
                          </div>
                          <div class="fav-info">
                              <span class="pull-left">' . $showTime . '</span>
                          </div>
                      </div>
                  </div>';
        }
        $address = UserAddress::find()->where(['uid' => $user_id])->orderBy(['type' => 'DESC', 'id' => 'DESC'])->asArray()->all();
        $userScore = LogUserScore::find()->where(['uid' => $user_id])->sum('score');
        //$str .= '<div class="col-md-12">' . (LinkPager::widget(['pagination' => $paginationExchange])) . '</div>';
        return $this->render('exchangeList', [
            'sidebar' => $this->sidebarStr,
            'htmlStr' => $str,
            'paginationExchange' => $paginationExchange,
            'address' => $address,
            'score' => $userScore,
        ]);
    }

    //积分兑换
    public function actionExchange()
    {
        if (Yii::$app->request->isPost) {
            $uid = Yii::$app->user->identity->id;
            $exchangeId = Yii::$app->request->post('exchangeId');
            $addressId = Yii::$app->request->post('addressId');

            $number = 1;

            $ret = array();
            $ret['data'] = array();

            if ($uid <= 0) {
                $ret['status'] = -1;
                $ret['message'] = '用户不存在';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            $nowTime = time();
            $scoreExchange = PrfScoreExchange::find()
                ->where(['id' => $exchangeId])
                ->andWhere(['or', ['<', 'start_time', $nowTime], ['start_time' => 0]])
                ->andWhere(['or', ['>', 'end_time', $nowTime], ['end_time' => 0]])
                ->one();
            if (empty($scoreExchange)) {
                $ret['status'] = -1;
                $ret['message'] = "活动已经结束,无法兑换";
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            if ($number > $scoreExchange['last_total'] && intval($scoreExchange['total']) > 0) {
                $ret['status'] = -1;
                $ret['message'] = "已经没有库存了";
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            if (intval($scoreExchange['user_max_number']) > 0) {
                // 判定用户最多兑换数目
                $user_ex_num = PayScoreItem::find()
                    ->innerJoin(LogUserScore::tableName(), "pay_score_item.log_id = log_user_score.id AND log_user_score.uid = $uid")
                    ->where(['pay_score_item.ex_id' => $exchangeId])
                    ->andWhere(['<=', 'pay_score_item.logistics_state', 2])
                    ->sum('pay_score_item.number');

                if (intval($user_ex_num) >= intval($scoreExchange['user_max_number'])) {
                    $ret['status'] = -1;
                    $ret['message'] = "您最多可以兑换 " . $scoreExchange['user_max_number'] . " 件";
                    return json_encode($ret, JSON_UNESCAPED_UNICODE);
                }
            }

            $userall = LogUserScore::find()->where(['uid' => $uid])->sum('score');
            $usescore = $scoreExchange['integral'];
            if ($userall < $usescore) {
                $ret['status'] = -3;
                $ret['message'] = "金币不足";
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            $item_id = $scoreExchange['item_id'];
            $u_a = \common\models\UserAddress::findOne(['uid' => $uid, 'id' => $addressId]);
            $address = $u_a['area'] . " " . $u_a['address'];
            $mobile = trim($u_a['mobile']);
            if (empty($u_a) == true || empty($u_a['address']) == true || strlen($mobile) == 0) {
                $ret['status'] = -1;
                $ret['message'] = "请先设置收货地址.";
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            $address = $u_a['area'] . " " . $u_a['address'];
            $mobile = $u_a['mobile'];

            Yii::$app->db->createCommand("update prf_score_exchange set last_total = last_total - 1 where `id` = '$exchangeId'")->execute();

            $newlogid = new LogUserScore();
            $newlogid->uid = $uid;
            $newlogid->score = $usescore * -1;
            $newlogid->score_key = date('Y-m-d', time());
            $newlogid->time = time();
            $newlogid->state = 100;
            $newlogid->memo = "兑换单品: {$scoreExchange['item_id']} ,  $number 个";
            $newlogid->save();
            $newlogid = Yii::$app->db->getLastInsertID();

            $newscoreitem = new PayScoreItem();
            $newscoreitem->ex_id = $exchangeId;
            $newscoreitem->log_id = $newlogid;
            $newscoreitem->item_id = $item_id;
            $newscoreitem->number = $number;
            $newscoreitem->score = $usescore;
            $newscoreitem->accept_address = $address;
            $newscoreitem->accept_photo = $mobile;
            $newscoreitem->save();

            $ret['status'] = 1;
            $ret['message'] = '兑换成功';
            $ret['data']['integrals'] = $userall - $usescore;        // integrals | 数值 | 用户总积分
            return json_encode($ret, JSON_UNESCAPED_UNICODE);
        }
    }

    //我的优惠券
    public function actionMyCoupon()
    {
        $user_id = Yii::$app->user->identity->id;
        $pageSize = 6;
        if (Yii::$app->request->isAjax && Yii::$app->request->isPost) {
            $type = yii::$app->request->post('type');
            $page = Yii::$app->request->post('page');
            if ($type == 'my-coupon') {
                echo CouponModule::getMyCoupon($pageSize, $page);
                return;
            } elseif ($type == 'get-coupon') {
                echo CouponModule::getCoupon($pageSize, $page);
                return;
            }
        }

        return $this->render('coupon', [
            'sidebar' => $this->sidebarStr
        ]);
    }

    //领取优惠券
    public function actionGetCoupon()
    {
        if (Yii::$app->request->isPost) {
            $id = Yii::$app->request->post('id');
            $prfCoupon = PrfCoupon::findOne(['id' => $id]);
            $excode = Yii::$app->request->post('excode');
            $ret = array();
            if (empty($prfCoupon)) {
                $ret['status'] = 3;
                $ret['msg'] = '优惠券不存在';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
            //判断兑换码
            if ($prfCoupon->excode != trim($excode)) {
                $ret['status'] = 3;
                $ret['msg'] = '兑换码不正确';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            if ($prfCoupon->end_time < time() && $prfCoupon->end_time != 0) {
                $ret['status'] = 3;
                $ret['msg'] = '优惠券已经过期';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            $hadCouponNum = UserCoupon::find()->where(['coupon_id' => $prfCoupon->id, 'uid' => Yii::$app->user->identity->id])->count();
            if ($prfCoupon->user_max_number <= $hadCouponNum && $prfCoupon->user_max_number != 0) {
                $ret['status'] = 3;
                $ret['msg'] = '无法领取更多了';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            if ($prfCoupon->last_count <= 0 && $prfCoupon->totle_count > 0) {
                $ret['status'] = 3;
                $ret['msg'] = '没有库存了';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }

            $userCoupon = new UserCoupon();
            $userCoupon->uid = Yii::$app->user->identity->id;
            $userCoupon->coupon_id = $prfCoupon->id;
            $userCoupon->start_time = $prfCoupon->start_time;
            $userCoupon->end_time = $prfCoupon->end_time;
            $userCoupon->price = $prfCoupon->price;
            $userCoupon->action = $prfCoupon->action;
            $userCoupon->action_id = $prfCoupon->action_id;
            $userCoupon->url = $prfCoupon->url;
            if ($userCoupon->save()) {
                $hadCouponNum = UserCoupon::find()->where(['coupon_id' => $prfCoupon->id, 'uid' => Yii::$app->user->identity->id])->count();
                if ($prfCoupon->user_max_number <= $hadCouponNum && $prfCoupon->user_max_number != 0) {
                    $ret['status'] = 1;
                    $ret['msg'] = '成功，不能再领取了';
                    return json_encode($ret, JSON_UNESCAPED_UNICODE);
                } else {
                    $ret['status'] = 2;
                    $ret['msg'] = '领取成功';
                    return json_encode($ret, JSON_UNESCAPED_UNICODE);
                }
            } else {
                $ret['status'] = 3;
                $ret['msg'] = '领取失败';
                return json_encode($ret, JSON_UNESCAPED_UNICODE);
            }
        }
    }

    //修改密码
    public function actionModifyPassword()
    {
        $model = new modifyPassword();
        $request = YII::$app->request;
//         $model->load(Yii::$app->request->post());
//         $msg = $model->changePassword();
        //var_dump($model->errors);return;
        if ($request->isPost && $model->load(Yii::$app->request->post()) && $model->changePassword()) {
            Yii::$app->user->logout();
            return $this->goHome();
        } else {
            return $this->render('modifyPassword', [
                'sidebar' => $this->sidebarStr,
                'model' => $model
            ]);
        }
    }

    //我的足迹
    public function actionMyFoot()
    {
        $user_id = Yii::$app->user->identity->id;

        //单品数据
        $item = LogUserFootprint::find()->where(['uid' => $user_id, 'action' => 'item', 'del' => 0]);
        $itemCount = $item->count();
        $pageItem = new Pagination(['totalCount' => $itemCount, 'pageSize' => 8]);
        $items = $item
            ->orderBy(['calltime' => SORT_DESC])
            ->offset($pageItem->offset)
            ->limit($pageItem->limit)
            ->all();
        //添加图片地址 和 价格
        //print_r($items);return;
        foreach ($items as $k => $v) {
            $items[$k]['imgUrl'] = Image::findOne(['id' => $v->item0['img_small_id']])['url'];
            $items[$k]['price'] = $v['item0']['price_base'];
            //print_r($v->tz0['price_base']);
            //print_r($v->tz0['img_small_id']);return;
            //print_r(Image::findOne(['id'=>$v->tz0['img_small_id']])['url']);
        }

        return $this->render('myFoot', [
            'sidebar' => $this->sidebarStr,
            'items' => $items,
            'pageItem' => $pageItem,
            'type' => 'item'
        ]);
    }

    public function actionTz()
    {
        $user_id = Yii::$app->user->identity->id;
        //套装数据
        $tz = LogUserFootprint::find()->where(['uid' => $user_id, 'action' => 'set', 'del' => 0]);
        $tzCount = $tz->count();
        $pageTz = new Pagination(['totalCount' => $tzCount, 'pageSize' => 8]);
        $tzs = $tz
            ->orderBy(['calltime' => SORT_DESC])
            ->offset($pageTz->offset)
            ->limit($pageTz->limit)
            ->all();
        //添加图片地址 和 价格
        foreach ($tzs as $k => $v) {
            $tzs[$k]['imgUrl'] = Image::findOne(['id' => $v->tz0['img_small_id']])['url'];
            $tzs[$k]['price'] = $v->tz0['price_base'];
        }

        return $this->render('myFoot', [
            'sidebar' => $this->sidebarStr,
            'tzs' => $tzs,
            'pageTz' => $pageTz,
            'type' => 'tz',
        ]);
    }

    public function actionShow()
    {
        $user_id = Yii::$app->user->identity->id;

        //show 数据
        $show = LogUserFootprint::find()->where(['uid' => $user_id, 'action' => 'show', 'del' => 0]);
        $showCount = $show->count();
        $pageShow = new Pagination(['totalCount' => $showCount, 'pageSize' => 8]);
        $shows = $show
            ->orderBy(['calltime' => SORT_DESC])
            ->offset($pageShow->offset)
            ->limit($pageShow->limit)
            ->all();
        //添加图片地址
        foreach ($shows as $k => $v) {
            $shows[$k]['imgUrl'] = Image::findOne(['id' => $v->show0['img_small_id']])['url'];
        }

        return $this->render('myFoot', [
            'sidebar' => $this->sidebarStr,
            'shows' => $shows,
            'pageShow' => $pageShow,
            'type' => 'show'
        ]);
    }

    //删除足迹记录
    public function actionDeleteFoot()
    {
        $postId = Yii::$app->request->post('id');
        $foot = LogUserFootprint::findOne(['id' => $postId]);
        $foot->del = 1;
        if ($foot->save()) {
            echo 1;
        } else {
            echo 0;
        }
    }

    //显示我的账户
    public function actionMyAccount()
    {
        $user_id = Yii::$app->user->identity->id;
        if ($user_id) {
            $user_info = new UserInfo();
            $user_info_ex = new UserInfoEx();
            $model = $user_info->findOne(['id' => $user_id]);
            $model_ex = $user_info_ex->getInfoEx($user_id);
            return $this->render('index', [
                'sidebar' => $this->sidebarStr,
                'model' => $model,
                'model_ex' => $model_ex
            ]);
        }
    }

    //显示我的地址
    public function actionMyAddress()
    {
        $addressForm = new AddressForm();

        if (Yii::$app->request->isAjax && (Yii::$app->request->post('operate') == 'delete')) {
            $id = Yii::$app->request->post('id');
            $userAddr = UserAddress::findOne(['id' => $id]);
            if ($userAddr->type == 1) {
                $res = [
                    'status' => 0,
                    'message' => '默认地址无法删除'
                ];
                return json_encode($res, JSON_UNESCAPED_UNICODE);
            }

            if (AddressForm::deleteAddress($id)) {
                $res = [
                    'status' => 1,
                    'message' => '删除成功'
                ];
                return json_encode($res, JSON_UNESCAPED_UNICODE);
            } else {
                $res = [
                    'status' => 0,
                    'message' => '删除失败'
                ];
                return json_encode($res, JSON_UNESCAPED_UNICODE);
            }
        }

        elseif (Yii::$app->request->get('operate') == 'edit') {
            $data = UserAddress::find()->where(['id' => Yii::$app->request->get('id')])->asArray()->all();
        }

        elseif (Yii::$app->request->get('operate') == 'default') {
            if (AddressForm::setDefault(Yii::$app->request->get('id'))) {
                $this->redirect(['account/my-address']);
                return;
            }
        }

        elseif (Yii::$app->request->isPost) {
            if ($addressForm->load(Yii::$app->request->post())) {
                $addressForm->addAddress();
                $this->redirect(['account/my-address']);
                return;
            }
        }

        $address = new UserAddress();
        $dataProvider = $address->search();

        return $this->render('address', [
            'sidebar' => $this->sidebarStr,
            'addressForm' => $addressForm,
            'dataProvider' => $dataProvider,
            'searchModel' => $address,
            'data' => isset($data) ? $data[0] : null,
        ]);
    }

    //ajax取城市
    public function actionCity()
    {
        if (Yii::$app->request->isAjax && Yii::$app->request->post('id')) {
            if (Yii::$app->request->post('q') == 'city') {
                $value = GrpCity::city(intval(Yii::$app->request->post('id')));
            } elseif (Yii::$app->request->post('q') == 'area2') {
                $value = GrpCity::area2(intval(Yii::$app->request->post('id')));
            } elseif (Yii::$app->request->post('q') == 'area') {
                $value = GrpCity::area(intval(Yii::$app->request->post('id')));
            }
            echo json_encode($value, JSON_UNESCAPED_UNICODE);
        }
    }

    //申请VIP会员
    public function actionApplyDesigner()
    {
        $model = SysUserDesigner::findOne(['uid' => Yii::$app->user->identity->id]);

        if (empty($model)) {
            $model = new SysUserDesigner();
            $model->setScenario('create');
            $model->uid = Yii::$app->user->identity->id;
        }
        $model->setScenario('create');

        $user_model = UserInfo::findOne(['id' => Yii::$app->user->identity->id]);
        $user_model->setScenario('apply-designer');

        if (
            $model->load(Yii::$app->request->post())
            && (!empty($user_model->tel) || ($user_model->load(Yii::$app->request->post()) && $user_model->validate()))
            )
        {
            $model->imageFile_idcard_a = UploadedFile::getInstanceByName('SysUserDesigner[imageFile_idcard_a]');
            $model->imageFile_idcard_b = UploadedFile::getInstanceByName('SysUserDesigner[imageFile_idcard_b]');
            $model->imageFile_bcard = UploadedFile::getInstanceByName('SysUserDesigner[imageFile_bcard]');

            if ($model->validate()) {
                if ($model->upload()) {
                    if ($model->concatAddress())
                    {
                        //重新提交 审核状态改为0
                        $model->audit_state = 0;
                        //用户状态改为申请中
                        $user_model->user_type = 2;
                        if ($model->save(false) && $user_model->save(false)) {
                            return $this->render('submitSuccess', [
                                'status' => 'success',
                                'redirectUrl' => Url::to(['account/my-account']),
                                'msg' => "提交成功，正在跳转……"
                            ]);
                        } else {
                            return $this->render('submitSuccess', [
                                'status' => 'warning',
                                'redirectUrl' => Url::to(['account/apply-designer']),
                                'msg' => "保存失败"
                            ]);
                        }
                    } else {
                        return $this->render('submitSuccess', [
                            'status' => 'warning',
                            'redirectUrl' => Url::to(['account/apply-designer']),
                            'msg' => "地址不正确"
                        ]);
                    }
                } else {
                    return $this->render('submitSuccess', [
                        'status' => 'warning',
                        'redirectUrl' => Url::to(['account/apply-designer']),
                        'msg' => "上传失败"
                    ]);
                }
            }

        }
        return $this->render('applyDesigner', [
            'sidebar' => $this->sidebarStr,
            'model' => $model,
            'user_model' => $user_model,
        ]);

    }

    //添加收藏
    public function actionAddFavourite()
    {
        if (Yii::$app->request->isAjax && Yii::$app->request->isPost) {
            $uid = Yii::$app->user->identity->id;
            $type_id = intval(Yii::$app->request->post('type_id'));
            $type = intval(Yii::$app->request->post('type'));

            $fav = new UserFavourite();
            $fav->uid = $uid;
            $fav->type = $type;
            $fav->type_id = $type_id;
            $fav->addtime = time();
            echo $fav->save() ? 1 : 0;
        }
    }
    //删除收藏
    public function actionRemoveFavourite()
    {
        $uid = Yii::$app->user->identity->id;
        $type_id = intval(Yii::$app->request->post('type_id'));
        $type = intval(Yii::$app->request->post('type'));

        $result = UserFavourite::deleteAll(['uid' => $uid, 'type_id' => $type_id, 'type' => $type]);
        echo $result ? 1 : 0;
    }

    //显示我的收藏
    public function actionMyFavourite()
    {
        $user_id = Yii::$app->user->identity->id;
        $pageSize = 20;
        if (Yii::$app->request->isAjax && Yii::$app->request->isPost) {
            $page = Yii::$app->request->post('page');
            $type = yii::$app->request->post('type');
            if ($type == 'item') {
                echo FavouriteModule::getItems($page, $pageSize);
                return;
            } elseif ($type == 'tz') {
                echo FavouriteModule::getTzs($page, $pageSize);
                return;
            } elseif ($type == 'showhome') {
                echo FavouriteModule::getShowHomes($page, $pageSize);
                return;
            }
        }

        return $this->render('favourite', [
            'sidebar' => $this->sidebarStr,
        ]);
    }

    //显示购物车
    public function actionMyShoppingCar()
    {
        $user_shopping_cart = new UserShoppingCart();
        $cart_arr = $user_shopping_cart->getShoppingCartAll();
        return $this->render('shoppingcart', [
            'sidebar' => $this->sidebarStr,
            'cart_arr' => $cart_arr
        ]);
    }

    //删除购物车
    public function actionDeleteFromCart()
    {
        $cartIdArray = json_decode(Yii::$app->request->post('cart_id_array'), true);
        echo UserShoppingCart::deleteCart($cartIdArray) ? 1 : 0;
    }

    //提交购物车
    public function actionSubmitCart()
    {
        //判断是否登录
        if (Yii::$app->getUser()->isGuest) {
            return $this->redirect(['site/login']);
        }
        $user_id = Yii::$app->getUser()->identity->getId();

        //传过来的order 包含所需的信息
        if (!Yii::$app->request->isPost && !Yii::$app->request->post('order')) {
            return $this->redirect(Url::to(['account/my-shopping-car']));
        }
        $order = json_decode(Yii::$app->request->post('order'), true);
        //为order 添加详细的单品信息
        foreach($order as $type => $value) {//obj 里面添加了单品信息
            foreach ($value as $key => $val) {
                $order[$type][$key]["items"] = SysItem::parseItem($order[$type][$key]["items"],true);
            }
        }

        //用户地址
        $userAddress = UserAddress::find()->where(['uid' => Yii::$app->user->identity->id])->asArray()->all();

        //用户等级 类别
        $user = UserInfo::findOne(['id' => Yii::$app->user->identity->id]);
        $user_type = $user->user_type;
        $user_type_class = $user->user_type_class;
        $user_discount = UserInfo::getUserDiscount($user_type, $user_type_class);

        //用户服务默认为0（含服务）
        $post_sales_service=!empty($user_discount)?($user_discount[1]['service']?$user_discount[1]['service']:0):0;

        $coupon_type = $this->coupon_type;

        $action_arr = []; //储存购物车里的单品id
        $id_count_arr = []; //储存单品 id =>数量  ['item id' => count]
        foreach ($order as $type => $type_value) //对 singleItem 和 tz 进行循环   用于计算 $action_arr  $id_count_arr
        {
            foreach($type_value as $key1 => $value1)// 对 singleItem 或 tz 里面的单品进行循环
            {
                if (!isset($action_arr[$coupon_type[$type]])){
                    $action_arr[$coupon_type[$type]] = [];
                }
                if (!isset($id_count_arr[$coupon_type[$type]])) {
                    $id_count_arr[$coupon_type[$type]] =[];
                }
                if ($coupon_type[$type] != 'set')
                {
                    foreach($value1["items"] as $key2 => $v) //此循环会判断同一件单品的id 然后$id_count_arr 添加单品的数量
                    {
                        $action_arr[$coupon_type[$type]][]=$v['item_id'];
                        if(isset($id_count_arr[$coupon_type[$type]][$v['item_id']])){
                            $id_count_arr[$coupon_type[$type]][$v['item_id']]=$id_count_arr[$coupon_type[$type]][$v['item_id']]+$v['count'];
                        }else{
                            $id_count_arr[$coupon_type[$type]][$v['item_id']]=$v['count'];
                        }
                    }
                }
                elseif ($coupon_type[$type] == 'set')
                {
                    $action_arr[$coupon_type[$type]][]=$value1['info']['id'];
                    if (isset($id_count_arr[$coupon_type[$type]][$value1['info']['id']])) {
                        $id_count_arr[$coupon_type[$type]][$value1['info']['id']]=$id_count_arr[$coupon_type[$type]][$value1['info']['id']]+$value1['info']['count'];
                    }else{
                        $id_count_arr[$coupon_type[$type]][$value1['info']['id']]=$value1['info']['count'];
                    }
                }

            }
        }

        //找出单品和套装优惠券
        $coupon=[];
        $coupon['item'] = !empty($action_arr['item'])?PrfCoupon::getItemCoupon($action_arr['item'], $user_id, $id_count_arr['item']):[];
        $coupon['set'] =  !empty($action_arr['set'])?PrfCoupon::getTzCoupon($action_arr['set'], $user_id, $id_count_arr['set']):[];
        //找出品牌优惠券
        $coupon['brand'] = !empty($action_arr['item'])?PrfCoupon::getBrandCoupon($action_arr['item'],$user_id, $id_count_arr['item']):[];
        $coupon['class'] = !empty($action_arr['item'])?PrfCoupon::getClassCoupon($action_arr['item'],$user_id, $id_count_arr['item']):[];
        //找出全场优惠券
        $coupon['all']   = PrfCoupon::getAllCoupon($user_id);


        Yii::$app->session['order_arr'] = $action_arr;

        return $this->render('confirmOrder', [
            'sidebar' => $this->sidebarStr,
            'item_info' => Yii::$app->request->post('order'),
            'obj' => json_encode($order, JSON_UNESCAPED_UNICODE),
            'user_discount' => $user_discount,
            'userAddress' => $userAddress,
            'user_type' => $user_type,
            'action_arr' => $action_arr,
            'coupon_type' => $coupon_type,
            'coupon' => json_encode($coupon, JSON_UNESCAPED_UNICODE),
            'cart_type' => json_encode($this->cart_map, JSON_UNESCAPED_UNICODE),
            'post_sales_service' => $post_sales_service
        ]);
    }

    //提交订单
    public function actionSubmitOrder()
    {
        if (Yii::$app->request->isPost) {
            $user_id = Yii::$app->user->identity->id;
            $item_info = json_decode(Yii::$app->request->post('item_info'), true);
            $user_info = json_decode(Yii::$app->request->post('user_info'), true);
            $coupon = json_decode(Yii::$app->request->post('coupon'), true);
            $design_serve = Yii::$app->request->post('post_sales_service');
            $total_price = Yii::$app->request->post('total_price');
            $this->submitOrder($user_id, $user_info['address_id'], $user_info['msg'], $item_info, $design_serve, $coupon, $total_price);

        } else {
            echo "提交错误";
            return;
            return $this->render('errorSubmit');
        }
    }

    //购物车提交后显示支付方式选择页面

    public function actionSubmitResult()
    {
        $trade_no = Yii::$app->request->get('trade_no') ? Yii::$app->request->get('trade_no') : Yii::$app->request->post('trade_no');
        $result = Yii::$app->request->get('result') ? Yii::$app->request->get('result') : Yii::$app->request->post('result');
        $res = PayTrade::findOne(['trade_no' => $trade_no, 'user_id' => Yii::$app->user->identity->id]);
        //var_dump(empty($res));return;
        if (!empty($res)) {
            $record = LogPay::find()->where(['trade_no' => $trade_no, 'uid' => Yii::$app->user->identity->id])->andWhere(['in', 'state', [1, 2]]);
            $trade_no_count = $record->max('trade_no_count');
            $sum_rmb = $record->sum('rmb');//已经付了了的钱
            $totalPrice = $res["price_modify"];//修改后的定价
            if ($trade_no_count == null) {//没付款 一半的价格
                $pay_price = $totalPrice / 2;
            } else {
                $result = -1;//第二次付款不再显示订单提交状态
                $pay_price = $totalPrice - $sum_rmb; //第二次付款 剩余的价格
            }
            return $this->render('submitResult', [
                'result' => $result,
                'trade_no' => $trade_no,
                'trade_no_count' => $trade_no_count,
                'sum_rmb' => $sum_rmb,
                'pay_price' => $pay_price,
                'enquiry' => $res['trade_state'],
                'sidebar' => $this->sidebarStr,
                'totalPrice' => $totalPrice
            ]);
        }
    }

    //显示订单列表
    public function actionOrderList()
    {
        $payTrade = new PayTrade();
        $all = $payTrade->find()->where(['user_id' => Yii::$app->user->identity->id])->count();
        $pagination = new Pagination([
            'totalCount' => $all,
            'pageSize' => 10
        ]);

        $model = $payTrade->find()->with(['rmb0'])->where(['user_id' => Yii::$app->user->identity->id])->orderBy(['id' => SORT_DESC])->offset($pagination->offset)->limit($pagination->limit)->asArray()->all();
        foreach ($model as $orderIndex => $orderObj) {
            //已经支付的价格
            if (!empty($orderObj['rmb0'])) {
                $paidRmb = 0;
                foreach ($orderObj['rmb0'] as $key => $val) {
                    $paidRmb += $val['rmb'];
                }
                $model[$orderIndex]['rmb'] = $paidRmb;
            } else {
                $model[$orderIndex]['rmb'] = 0;
            }
            $model[$orderIndex]['content'] = json_decode($orderObj['content'], true);
            foreach ($model[$orderIndex]['content'] as $type => $obj) {
                foreach ($obj as $index => $items) {
                    if ($type == 'tz' || isset($items['info']['cart_type']) && $items['info']['cart_type'] == 1) {
                        $res = TaoZhuang::findOne(['sid' => $items['info']['id']]);
                        $model[$orderIndex]['content'][$type][$index]['info']['name'] = $res['name'];
                    }
                    if (isset($items['items'])) {
                        foreach ($items['items'] as $key => $value) {
                            $res = ActiveRecord::findBySql('SELECT sys_image.url FROM `sys_item` LEFT JOIN sys_image ON sys_item.img_small_id = sys_image.id WHERE sys_item.id = ' . $value['item_id'])->asArray()->all();
                            $model[$orderIndex]['content'][$type][$index]['items'][$key]['img_url'] = $res[0]['url'];
                        }
                    }
                }
            }
            //print_r($model[$orderIndex]['content']);
        }
        return $this->render('orderList', [
            'model' => $model,
            'pagination' => $pagination,
            'sidebar' => $this->sidebarStr,
        ]);
    }


    public function actionOrderRefundApply()
    {
        $trade_no = Yii::$app->request->post('trade_no');
        $one_trade = PayTrade::findOne(['trade_no' => $trade_no, 'user_id' => Yii::$app->user->identity->id]);
        //订单不存在
        if (empty($one_trade)) {
            $res['status_time'] = -1;
            $res['order_desc'] = '订单不存在';
            return json_encode($res);
        }
        //订单未付款
        if (!(intval($one_trade['price_state']) == 1 || intval($one_trade['price_state']) == 11) && intval($one_trade['trade_state']) != 1) {
            $re['status_time'] = -2;
            $res['order_desc'] = '订单未付款';
            return json_encode($res);
        }
        //获取付款时间
        $res = PayTrade::getRefundPrice($trade_no);
        return json_encode($res);
    }

    public function actionOrderLogisticsQuery()
    {
        //print_r(Yii::$app->request->post());return;
        if (Yii::$app->request->isPost) {
            $ret = array();
            $ret['data'] = array();


            if (Yii::$app->user->identity->id < 0) {
                $ret['status'] = -1;
                $ret['message'] = '用户不存在或未登陆';
                return json_encode($ret);
            }
            $out_trade_no = Yii::$app->request->post('trade_no');
            $one_trade = PayTrade::findOne(['trade_no' => $out_trade_no]);

            if (intval($one_trade['trade_state'] != 7)) {
                $ret['status'] = -2;
                $ret['message'] = '订单状态错误';
                return json_encode($ret);
            }

            $logistics = PayLogistics::findAll(['trade_id' => $one_trade['id']]);
            $ret['logistics_status'] = array();
            $record = array();
            foreach ($logistics as $k => $val) {
                $waybill_number = $val->logistics_trade;
                $logistics_name = $val->logistics_name;
                if (in_array($waybill_number, $record)) {
                    continue;
                } else {
                    $record[$k] = $waybill_number;
                }
                if ($logistics_name != '其它') {
                    $kd = GrpKuaidi::findOne(['code' => $logistics_name]);
                    if (empty($kd)) {
                        $ret['status'] = -997;
                        $ret['message'] = "快递公司编码错误:" . $logistics_name;
                        return json_encode($ret);
                    }
                }

                if (strlen($logistics_name) == 0) {
                    $ret['status'] = -997;
                    $ret['message'] = "快递公司编码错误:" . $logistics_name;
                    return json_encode($ret);
                }

                if ($logistics_name == '其它') {
                    $ret['logistics_status'][$k]['state'] = 0;
                    $ret['logistics_status'][$k]['company'] = '自营物流';
                    $ret['logistics_status'][$k]['logisticsId'] = $waybill_number;
                    $ret['logistics_status'][$k]['memo'] = array();
                    $ret['logistics_status'][$k]['memo'][0] = $val->item_memo;
                    continue;
                }
                $data = null;

                try {
                    //参数设置
                    $post_data = array();
                    $post_data["customer"] = 'DB18967F63113F1BF97A0AC6773E31C5';
                    $key = 'YjPgYUqw7427';
                    $post_data["param"] = '{"com":"' . $logistics_name . '","num":"' . $waybill_number . '"}';

                    $url = 'http://poll.kuaidi100.com/poll/query.do';
                    $post_data["sign"] = md5($post_data["param"] . $key . $post_data["customer"]);
                    $post_data["sign"] = strtoupper($post_data["sign"]);

                    $data = json_decode(self::request_post($url, $post_data), true);

                } catch (Exception $e) {
                    $ret['status'] = -999;
                    $ret['message'] = $e->getMessage();
                    return json_encode($ret);
                }
                if (is_null($data)) {
                    $ret['status'] = -998;
                    $ret['message'] = "获取失败";
                    return json_encode($ret);
                }
                if (array_key_exists('returnCode', $data) == true && array_key_exists('state', $data) == false) {
                    continue;
                    $ret['status'] = $data['returnCode'];
                    $ret['message'] = $data['message'];
                    return json_encode($ret);
                }

                self::util_set_LOGISTICS_STATUS($ret['logistics_status'][$k], $data, $kd['name']);
                self::logItemMsg($ret['logistics_status'][$k], $val, $waybill_number);
            }

//            return json_encode($ret, JSON_UNESCAPED_UNICODE);
            return $this->render('logisticsQuery', [
                'sidebar' => $this->sidebarStr,
                'ret' => $ret,
            ]);
        }

    }

    public function logItemMsg(&$arr, $item, $waybill_number)
    {
        $payLogistics = PayLogistics::findAll(['logistics_trade' => $waybill_number]);
        $arr['memo'] = array();
        foreach ($payLogistics as $ke => $val) {
            $arr['memo'][$ke] = $val->item_memo;
        }
    }

    // 模拟post进行url请求  拼接url封装起来
    public function request_post($url, $post_data)
    {
        if (empty($url) || empty($post_data)) {
            return false;
        }

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        if (gettype($post_data) == "string") {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, self::getParamAuto($post_data));
        }
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }

    // 按照字典顺序 a-z 排列参数
    function getParamAuto($param, $url_encode_flg = true)
    {
        $rnt = "";
        while (true) {
            if (is_null($param) || !is_array($param) || count($param) == 0) break;

            $sm = "";
            foreach ($param as $k => $v) {
                if (strlen($sm) == 0) {
                    $sm = $k;
                } else {
                    if (strcmp($sm, $k) > 0) {
                        $sm = $k;
                    }
                }
            }
            if ($url_encode_flg)
                $rnt .= "$sm=" . urlencode($param[$sm]) . "&";
            else
                $rnt .= "$sm=" . $param[$sm] . "&";
            unset($param[$sm]);
        }
        return substr($rnt, 0, -1);
    }

    public function util_set_LOGISTICS_STATUS(&$arr, $jsonarray, $kdname = '')
    {
        $arr['state'] = $jsonarray['state'];
        $arr['company'] = $kdname == '' ? $jsonarray['com'] : $kdname;
        $arr['logisticsId'] = $jsonarray['nu'];

        $arr['logisticsArray'] = array();
        foreach ($jsonarray['data'] as $ar) {
            $a = array();
            self::util_set_LOGISTICS_TRACKING($a[], $ar);
            $arr['logisticsArray'][] = $a;
        }
    }

    public function util_set_LOGISTICS_TRACKING(&$arr, $dataitem)
    {
        $arr['context'] = $dataitem['context'];
        $arr['time'] = $dataitem['ftime'];
    }

    public function actionOrderOperate()
    {
        $allowArr = [
            '0' => [1, 2],//待付款
            '1' => [1, 3],
            '2' => [4],
            '3' => [4, 5, 7],
            '4' => [6],
            '5' => [4],
            '6' => [1],
            '7' => [1, 8, 9],
        ];
        $state = Yii::$app->request->post('state');
        $operate = intval(Yii::$app->request->post("operate"));
        $trade_no = Yii::$app->request->post('trade_no');
        $option = Yii::$app->request->post('option');
        if (in_array($operate, $allowArr[$state])) {
            switch ($operate) {
                case 1:
                    break;//联系卖家
                case 2:
                    echo PayTrade::closeOrder($operate, $trade_no, $option);
                    break;//取消订单
                case 3:
                    echo PayTrade::orderOperate($operate, $trade_no);
                    break;//申请退款
                case 4:
                    echo PayTrade::deleteOrder($operate, $trade_no);
                    break;//删除订单
                case 5:
                    break;//申请售后
                case 6:
                    break;//取消申请售后
                case 7:
                    break;//评价
                case 8:
                    break;//查看物流
                case 9:
                    echo PayTrade::reciveOrder($operate, $trade_no);
                    break;//确认收货
            }
        } else {
            echo 0;
        }
    }

    //编辑账户信息
    public function actionEditAccountInfo()
    {
        $user_id = Yii::$app->user->identity->id;
        if (Yii::$app->request->post()) {
            $info = array();
            $info_ex = array();
            if (Yii::$app->request->post('Signature')) {
                $info_ex['user_label'] = Yii::$app->request->post('Signature');
            }
            if (Yii::$app->request->post('Introductions')) {
                $info_ex['user_memo'] = Yii::$app->request->post('Introductions');
            }
            if (Yii::$app->request->post('Firstname')) {
                $info_ex['firstname'] = Yii::$app->request->post('Firstname');
            }
            if (Yii::$app->request->post('Nickname')) {
                $info['nickname'] = Yii::$app->request->post('Nickname');
            }
            if (Yii::$app->request->post('Birthday')) {
                $info_ex['birthday'] = Yii::$app->request->post('Birthday');
            }
            if (Yii::$app->request->post('Sex')) {
                $info_ex['user_sex'] = Yii::$app->request->post('Sex');
            }
            if ($email = Yii::$app->request->post('Email')) {
                $userInfo = UserInfo::updateAll(['email' => $email],['id' => Yii::$app->user->id]);
            }
            $user = User::findOne(['id' => $user_id]);
            foreach ($info as $key => $value) {
                $user->$key = $value;
                $user->update();
            }
            foreach ($info_ex as $key => $value) {
                UserInfoEx::deleteAll('user_id=:id AND u_key=:key', [':id' => $user_id, ':key' => $key]);
                $user = new UserInfoEx();
                $user->user_id = $user_id;
                $user->u_key = $key . '';
                $user->u_value = $value . '';
                $user->save();
            }
            $this->redirect(['account/my-account']);
            return;
        }
        if ($user_id) {
            $user_info = new UserInfo();
            $user_info_ex = new UserInfoEx();
            $model = $user_info->findOne(['id' => $user_id]);
            $model_ex = $user_info_ex->getInfoEx($user_id);
            return $this->render('editAccountInfo', ['sidebar' => $this->sidebarStr, 'model' => $model, 'model_ex' => $model_ex]);
        }
    }

    //邀请好友
    public function actionInvitedFriend()
    {
        $pageSize = 10;
        $uid = Yii::$app->user->identity->id;

        $sql_count = "SELECT count(*)
            FROM user_invite invite0 LEFT JOIN user_invite invite1 ON invite1.invite_f = invite0.invite
            WHERE invite0.invite_f = (SELECT invite FROM `user_invite` WHERE uid = " . $uid . ")
            GROUP BY invite0.invite";

        $t = ActiveRecord::findBySql($sql_count)->asArray()->all();

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => count($t)
        ]);

        $sql = "SELECT user_info.username,
                     user_info.created_at,
                     COUNT(invite1.invite_f) AS invited_count,
                     user_invite_totle.my_payamounts AS one_pay
            FROM user_invite invite0
            LEFT JOIN user_invite invite1 ON invite1.invite_f = invite0.invite 
            LEFT JOIN user_info ON invite0.uid=user_info.id 
            LEFT JOIN user_invite_totle ON invite0.uid = user_invite_totle.uid
            WHERE invite0.invite_f = (SELECT invite FROM `user_invite` WHERE uid = " . $uid . ")
            GROUP BY invite0.invite ORDER BY user_info.created_at DESC LIMIT " . $pagination->offset . "," . $pagination->limit;
        $arr = ActiveRecord::findBySql($sql)->asArray()->all();

        $sql = "SELECT user_invite_totle.my_payamounts
                       FROM user_invite_totle WHERE user_invite_totle.uid = " . $uid;
        $myPay = ActiveRecord::findBySql($sql)->asArray()->one();

        return $this->render('invitedFriend', [
            'sidebar' => $this->sidebarStr,
            'pagination' => $pagination,
            'data' => $arr,
            'myPay' => $myPay
        ]);
    }

    //上传头像
    public function actionUploadAvatar()
    {
        $user_id = Yii::$app->user->identity->id;
        $large_img = Yii::$app->request->post("large_img");
        $img_id = $this->convertToImg($large_img);
        if ($img_id && $user_id) {
            UserInfoEx::deleteAll('user_id=:id AND (u_key="img_small_id" or u_key="img_thumb_id" or u_key="img_url_id")', [':id' => $user_id]);
            $user_info_ex1 = new UserInfoEx();
            $user_info_ex1->user_id = $user_id;
            $user_info_ex1->u_key = 'img_small_id';
            $user_info_ex1->u_value = $img_id;
            $user_info_ex1->save();
            $user_info_ex2 = new UserInfoEx();
            $user_info_ex2->user_id = $user_id;
            $user_info_ex2->u_key = 'img_thumb_id';
            $user_info_ex2->u_value = $img_id;
            $user_info_ex2->save();
            $user_info_ex3 = new UserInfoEx();
            $user_info_ex3->user_id = $user_id;
            $user_info_ex3->u_key = 'img_url_id';
            $user_info_ex3->u_value = $img_id;
            $user_info_ex3->save();
            $user_info = new UserInfo();
            $user_info_ex = new UserInfoEx();
            $model = $user_info->findOne(['id' => $user_id]);
            $model_ex = $user_info_ex->getInfoEx($user_id);

            return isset($model_ex['img_url_id']) ? Yii::$app->params['imgPath0'] . $model_ex['img_url_id'] : Yii::$app->params['imgPath0'] . Yii::$app->params['defaultImg'];
        }
    }

    private function convertToImg($base64Steam)
    {
        $base64Steam = str_replace(' ', '+', $base64Steam);
        $img_type = explode(';', $base64Steam, 2);
        $img_type = explode('/', $img_type[0]);
        if ($img_type[1] == 'jpeg') {
            $img_type = 'jpg';
            $data = base64_decode(str_replace('data:image/jpeg;base64,', '', $base64Steam));
        } elseif ($img_type[1] == 'png') {
            $img_type = 'png';
            $data = base64_decode(str_replace('data:image/png;base64,', '', $base64Steam));
        } elseif ($img_type[1] == 'bmp') {
            $img_type = 'bmp';
            $data = base64_decode(str_replace('data:image/bmp;base64,', '', $base64Steam));
        }
        if ($data) {
            $result = PrfType::find()->where(['id' => '413'])->one();
            $uuid = md5(uniqid());
            $uuid_a = substr($uuid, 0, 3);
            $uuid_b = substr($uuid, 3, 3);
            $uuid_c = substr($uuid, 6, 3);
            $uuid_d = substr($uuid, 9, 3);
            $dir = 'images/' . $result->addr . '/' . $uuid_a . '/' . $uuid_b . '/' . $uuid_c . '/' . $uuid_d . '/';
            mkdir('../../backend/web/' . $dir, 0777, true);
            $name = substr($uuid, 12, 20);
            $path = '../../backend/web/' . $dir . $name;
            file_put_contents($path . '.' . $img_type, $data);
            list($width, $height, $type, $attr) = getimagesize($path . '.' . $img_type);

            //文件传到app服务器
            $url = "https://app.jajahome.com/furniture/calc.php";
            if (class_exists('\CURLFile')) {
                $post_data = [
                    "q" => "uploadImg",
                    "dir" => $dir,
                    "name" => $name,
                    "file_type" => $img_type,
                    "img" => new \CURLFile($path . '.' . $img_type)
                ];
            } else {
                $post_data = [
                    "q" => "uploadImg",
                    "dir" => $dir,
                    "name" => $name,
                    "file_type" => $img_type,
                    "img" => "@" . realpath($path . '.' . $img_type)
                ];
            }

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $output = curl_exec($ch);
            curl_close($ch);

            if ($output == "done") {
                $new_img = new Image();
                $new_img->url = $dir . $name . '.' . $img_type;
                $new_img->width = intval($width);
                $new_img->height = intval($height);
                $new_img->name = Yii::$app->user->identity->id;
                $new_img->type = 413;
                if ($new_img->save(false)) {
                    $id = $new_img->id;
                    return $id;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }


    private function submitOrder1($user_id, $address_id, $message, $item_info)
    {
        $cart_id_array = array();
        $cart_id_index = 0;
        $consolt = 0;
        //生成订单号
        $row = UserInfo::findOne(['id' => $user_id]);
        $trade_no = substr($row["username"], -4, 4) . substr($row["id"], -4, 4) . strtotime("now");
        //用户身份类型
        $user_type = $row["user_type"];
        $user_type_class = $row['user_type_class'];
        //用户折扣
        $userDiscount = UserInfo::getUserDiscount($user_type, $user_type_class);
        //取得地址
        $address = UserAddress::getAddressStr($address_id);

        //计算价格
        $total_price = 0;
        $total_count = 0;

        //生成数据
        $content = array();
        $singleItemI = 0;
        $tzI = 0;
        foreach ($item_info as $key => $value) {
            $cart_id_array[$cart_id_index++] = $value['info']['cart_id'];
            unset($value['info']['cart_id']);
            if (isset($this->cart_map[$value['info']['cart_type']]) && isset($userDiscount[$this->cart_map[$value['info']['cart_type']]]['discount'])) {
                $value['info']['user_discount'] = floatval($userDiscount[$this->cart_map[$value['info']['cart_type']]]['discount']);
                $value['info']['sales_service'] = floatval($userDiscount[$this->cart_map[$value['info']['cart_type']]]['service']);
            } else {
                $value['info']['sales_service'] = 0;
            }
            foreach ($value['items'] as $x => $item) {
                //如果是赠品，仅计算final_price=0;
                if (isset($value["info"]["exclude"]) && in_array($item['item_id'], $value["info"]["exclude"])) {
                    $final_price = 0;
                } elseif (intval($item["price_base"])) {
                    //否则如果需要询价
                    //如果存在用户折扣
                    if (isset($userDiscount[$this->cart_map[$value['info']['cart_type']]]['discount'])) {
                        $final_price = intval(($item["price_base"] + $item["_price_custom"]) * $value['info']['user_discount']);
                    }//否则计算套装折扣
                    elseif (isset($value["info"]["discount"])) {
                        $discount = floatval($value["info"]["discount"]) == 0 ? 1 : floatval($value["info"]["discount"]);
                        $final_price = intval(($item["price_base"] * $item["price_discount"] + $item["_price_custom"] * $item["_price_discount"]) * $discount);
                    }//再否则计算单品本身折扣
                    else {
                        $final_price = intval($item["price_base"] * $item["price_discount"] + $item["_price_custom"] * $item["_price_discount"]);
                    }
                } else {
                    //如果price_base为0则必须待询价
                    $final_price = 0;
                    $consolt = 6;
                }
                //计算final_price，未乘info里的count
                $value['items'][$x]['final_price'] = $final_price;
                $t = $final_price * $item["count"];

                //如果info里有count，则再乘上此count
                if (isset($value["info"]['count']) && $value["info"]['count'] > 1) {
                    $total_price = $total_price + $t * intval($value["info"]['count']);
                    $total_count = $total_count + $item["count"] * intval($value["info"]['count']);
                } else {
                    $total_price = $total_price + $t;
                    $total_count = $total_count + $item["count"];
                }
                if (isset($value['items'][$x]['img_url'])) {
                    unset($value['items'][$x]['img_url']);
                }
            }
            if ($value['info']['cart_type'] == 0) {
                unset($value['info']['cart_type']);
                if (!isset($content['singleItem'])) {
                    $content['singleItem'] = array();
                }
                $content['singleItem'][$singleItemI] = [
                    'info' => $value['info'],
                    'items' => $value['items']
                ];
                $singleItemI++;
            } elseif ($value['info']['cart_type'] == 1) {
                unset($value['info']['cart_type']);
                if (!isset($content['tz'])) {
                    $content['tz'] = array();
                }
                $content['tz'][$tzI] = [
                    'info' => $value['info'],
                    'items' => $value['items']
                ];
                $tzI++;
            }
        }
        //print_r($content);return ;
        //写入数据库
        $order = new PayTrade();
        $order->trade_no = $trade_no;
        $order->user_id = $user_id;
        $order->address = $address;
        $order->message = $message;
        $order->number = $total_count;
        $order->price = $total_price;
        $order->price_modify = $total_price;
        $order->price_state = 0;
        $order->create_time = time();
        $order->modify_time = time();
        $order->trade_state = $consolt;
        $order->audit_state = 0;
        $order->content = json_encode($content, JSON_UNESCAPED_UNICODE);
        //print_r($order);return ;
        if ($order->save()) {
            $result = 1;
            //删除购物车
            UserShoppingCart::deleteCart($cart_id_array);
        } else {
            $result = 0;
        }
        if (isset(Yii::$app->session['order_arr'])) {
            unset(Yii::$app->session['order_arr']);
        }
        $this->redirect(Url::to(['account/submit-result', 'result' => $result, 'trade_no' => $trade_no, 'enquiry' => $consolt]));
    }
    private function submitOrder($user_id,$address_id,$message,$item_info,$design_serve,$coupon,$post_total_price)
    {
        $design_discount = 0.03;
        $cart_type = $this->cart_map;
        $cart_id_array=array();
        $cart_id_index=0;
        $consolt=0;//是否待改价

        //取得优惠券
        $coupon_arr=[];
        $item_id_arr=[];
        $item_count=[];
        $tz_id_arr=[];
        $tz_count=[];
        if (isset($item_info['singleItem'])) {
            foreach ($item_info['singleItem'] as $i => $value) {
                //找出所有单品id
                $item_id_arr[]=$value['items'][0]['item_id'];
                //找出所有单品数量
                if (!isset($item_count[$value['items'][0]['item_id']])) {
                    $item_count[$value['items'][0]['item_id']]=0;
                }
                $item_count[$value['items'][0]['item_id']]=$item_count[$value['items'][0]['item_id']]+$value['items'][0]['count'];
            }
            $coupon_arr['item'] = PrfCoupon::getItemCoupon($item_id_arr, $user_id, $item_count);
            $coupon_arr['class'] = PrfCoupon::getClassCoupon($item_id_arr, $user_id, $item_count);
            $coupon_arr['brand'] = PrfCoupon::getBrandCoupon($item_id_arr, $user_id, $item_count);
            $coupon_arr['all'] = PrfCoupon::getAllCoupon($user_id);
        }
        if (isset($item_info['tz'])) {
            foreach ($item_info['tz'] as $i => $value) {
                $tz_id_arr[]=$value['info']['id'];
                if (!isset($tz_count[$value['info']['id']])) {
                    $tz_count[$value['info']['id']]=0;
                }
                $tz_count[$value['info']['id']]=$tz_count[$value['info']['id']]+$value['info']['count'];
            }
            $coupon_arr['set'] = PrfCoupon::getTzCoupon($tz_id_arr, $user_id, $tz_count);
            $coupon_arr['all'] = PrfCoupon::getAllCoupon($user_id);
        }

        //筛选优惠券，优惠券都只有一张
        if (isset($coupon_arr['item']) && !empty($coupon_arr['item'])) {
            foreach ($coupon_arr['item'] as $id => $value) {
                if (in_array($id, $coupon)) {
                    $coupon_arr['item'] = $coupon_arr['item'][$id];
                    break;
                }else{
                    unset($coupon_arr['item'][$id]);
                }
            }
        }
        if (isset($coupon_arr['class']) && !empty($coupon_arr['class'])) {
            foreach ($coupon_arr['class'] as $id => $value) {
                if (in_array($id, $coupon)) {
                    $coupon_arr['class'] = $coupon_arr['class'][$id];
                    break;
                }else{
                    unset($coupon_arr['class'][$id]);
                }
            }
        }
        if (isset($coupon_arr['brand']) && !empty($coupon_arr['brand'])) {
            foreach ($coupon_arr['brand'] as $id => $value) {
                if (in_array($id, $coupon)) {
                    $coupon_arr['brand'] = $coupon_arr['brand'][$id];
                    break;
                }else{
                    unset($coupon_arr['brand'][$id]);
                }
            }
        }
        if (isset($coupon_arr['set']) && !empty($coupon_arr['set'])) {
            foreach ($coupon_arr['set'] as $id => $value) {
                if (in_array($id, $coupon)) {
                    $coupon_arr['set'] = $coupon_arr['set'][$id];
                    break;
                }else{
                    unset($coupon_arr['set'][$id]);
                }
            }
        }
        if (isset($coupon_arr['all']) && !empty($coupon_arr['all'])) {
            foreach ($coupon_arr['all'] as $id => $value) {
                if (in_array($id, $coupon)) {
                    $coupon_arr['all'] = $coupon_arr['all'][$id];
                    break;
                }else{
                    unset($coupon_arr['all'][$id]);
                }
            }
        }

        //生成订单号
        $row = UserInfo::findOne(['id' => $user_id]);
        $trade_no=substr($row["username"],-4,4).substr($row["id"],-4,4).strtotime("now");
        //用户身份类型
        $user_type=$row["user_type"];
        $user_type_class=$row['user_type_class'];
        //用户折扣
        $user_discount = UserInfo::getUserDiscount($user_type,$user_type_class);
        //取得地址
        $address = UserAddress::getAddressStr($address_id);

        //计算价格
        $total_price=0;
        $total_count=0;

        //解析item_info
        foreach ($item_info as $key => $obj)
        {
            foreach ($obj as $content_index => $content)
            {
                //判断服务类型
                if (isset($cart_type[$content['info']['cart_type']])&&isset($user_discount[$cart_type[$content['info']['cart_type']]]['service'])) {
                    $item_info[$key][$content_index]["info"]["sales_service"]=$user_discount[$cart_type[$content['info']['cart_type']]]['service'];
                }else{
                    $item_info[$key][$content_index]["info"]["sales_service"]=0;
                }
                //解析item详细信息
                $item_info[$key][$content_index]["items"] = SysItem::parseItem($content["items"]);
                if(isset($content["info"]["cart_id"])){
                    $cart_id_array[$cart_id_index++]=$content["info"]["cart_id"];
                    unset($item_info[$key][$content_index]["info"]["cart_id"]);
                }
                //如果存在用户折扣,折扣写进info里
                if (isset($user_discount[$cart_type[$content['info']['cart_type']]]['service']))
                {
                    $item_info[$key][$content_index]["info"]["user_discount"]=$user_discount[$cart_type[$content['info']['cart_type']]]['discount'];
                }
                //写入优惠券信息
                if ($key == 'singleItem') {
                    if (!empty($coupon_arr['item']) && $content['items'][0]['item_id']==$coupon_arr['item']['action_id']) {
                        $item_info[$key][$content_index]['info']['user_coupon_id']=$coupon_arr['item']['id'];
                    } elseif (!empty($coupon_arr['brand']) && $content['items'][0]['brand_id']==$coupon_arr['brand']['action_id']) {
                        $item_info[$key][$content_index]['info']['user_coupon_id']=$coupon_arr['brand']['id'];
                    } elseif (!empty($coupon_arr['class']) && $content['items'][0]['class_id']==$coupon_arr['class']['action_id']) {
                        $item_info[$key][$content_index]['info']['user_coupon_id']=$coupon_arr['class']['id'];
                    }
                }
                elseif ($key == 'tz' && !empty($coupon_arr['set']) && $content['info']['id']==$coupon_arr['set']['action_id']) {
                    $item_info[$key][$content_index]['info']['user_coupon_id']=$coupon_arr['set']['id'];
                }
                elseif (!empty($coupon_arr['all'])) {
                    $item_info[$key][$content_index]['info']['user_coupon_id']=$coupon_arr['all']['id'];
                }
            }
        }

        //计算价格
        $use_item_coupon = false;

        $item_total_price 	= 0;
        $item_total_count 	= 0;

        $tz_total_price 	= 0;
        $tz_total_count 	= 0;

        $total_class_price 	= 0;
        $total_brand_price 	= 0;
        $total_all_price	= 0;

        $total_price = 0;
        $total_count = 0;

        foreach ($item_info as $key => $obj)
        {
            if ($key == 'singleItem')
            {
                foreach ($obj as $content_index => $content)
                {
                    $item = $content['items'][0];
                    //如果是赠品，跳过计算
                    if (isset($content["info"]["exclude"])&&!empty($content["info"]["exclude"])&&in_array($item['item_id'],$content["info"]["exclude"])) {
                        $item_info[$key][$content_index]["items"][0]["final_price"]=0;
                        continue;
                    }
                    //如果存在单品优惠券
                    elseif (!empty($coupon_arr['item']) && isset($coupon_arr['item']['action_id']) && ($coupon_arr['item']['action_id']==$item['item_id'] || $coupon_arr['item']['action_id']==0) && !$use_item_coupon){
                        $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                        $item_total_price = $item_total_price + PrfCoupon::coupon_calc($item_info[$key][$content_index]["items"][0]["final_price"], $item['count'], $coupon_arr['item']);
                        $use_item_coupon = true;
                    }
                    //如果存在类目优惠券
                    elseif (!empty($coupon_arr['class']) && $item['class_id']==$coupon_arr['class']['action_id']) {
                        $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                        $total_class_price = $total_class_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item['count'];

                    }
                    //如果存在品牌优惠券
                    elseif (!empty($coupon_arr['brand']) && $item['brand_id']==$coupon_arr['brand']['action_id']) {
                        $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                        $total_brand_price = $total_brand_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item['count'];

                    }
                    //如果存在全场优惠券
                    elseif (!empty($coupon_arr['all'])) {
                        $item_info[$key][$content_index]["items"][0]["final_price"] = $item['price_base'] + $item['_price_custom'];
                        $total_all_price = $total_all_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item['count'];
                    }
                    //如果存在用户折扣
                    elseif (isset($user_discount[$cart_type[$content['info']['cart_type']]]['discount'])) {
                        $item_info[$key][$content_index]["items"][0]["final_price"]=(intval($item["price_base"])?round(($item["price_base"]+$item["_price_custom"])*($user_discount[$cart_type[$content['info']['cart_type']]]['discount']),2):0);
                        $item_total_price = $item_total_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item["count"];
                    }
                    //否则计算单品本身折扣
                    else{
                        $item_info[$key][$content_index]["items"][0]["final_price"]=(intval($item["price_base"])?round($item["price_base"]*$item["price_discount"]+$item["_price_custom"]*$item["_price_discount"],2):0);
                        $item_total_price = $item_total_price + $item_info[$key][$content_index]["items"][0]["final_price"] * $item["count"];
                    }

                    $total_count = $total_count + $item['count'];
                }

                $total_price = $total_price + $item_total_price;
                if ($use_item_coupon && !empty($coupon_arr['item'])) {
                    if(!isset($item_info['coupon'])){
                        $item_info['coupon']=[];
                    }
                    $item_info['coupon']['item']=$coupon_arr['item'];
                }
                //单品类目优惠
                if ($total_class_price && !empty($coupon_arr['class'])) {
                    $total_price = $total_price + PrfCoupon::coupon_calc($total_class_price, 1, $coupon_arr['class']);
                    if(!isset($item_info['coupon'])){
                        $item_info['coupon']=[];
                    }
                    $item_info['coupon']['item']=$coupon_arr['class'];
                }
                //单品品牌优惠
                if ($total_brand_price && !empty($coupon_arr['brand'])) {
                    $total_price = $total_price + PrfCoupon::coupon_calc($total_brand_price, 1, $coupon_arr['brand']);
                    if(!isset($item_info['coupon'])){
                        $item_info['coupon']=[];
                    }
                    $item_info['coupon']['item']=$coupon_arr['brand'];
                }
            }
            elseif ($key == 'tz') {

                $max_tz_price = 0;
                $max_tz_index = 0;

                $max_action_tz_price = 0;
                $max_action_tz_index = 0;

                foreach ($obj as $content_index => $content)
                {
                    $item_info[$key][$content_index]['info']['origin_price'] = 0;
                    $item_info[$key][$content_index]['info']['final_price'] = 0;
                    //先累加单品
                    $t_count = 0;

                    foreach ($content['items'] as $i => $item) {
                        //如果是赠品，跳过计算
                        $item_exclude = false;
                        if (isset($content["info"]["exclude"])&&!empty($content["info"]["exclude"])&&in_array($item['item_id'],$content["info"]["exclude"])) {
                            $item_info[$key][$content_index]["items"][$i]["final_price"] = 0;
                            $item_exclude = true;
                        }
                        //如果有用户折扣
                        elseif (isset($user_discount[$cart_type[$content['info']['cart_type']]]['discount'])) {
                            $item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"])?round(($item["price_base"] + $item["_price_custom"]) * ($user_discount[$cart_type[$content['info']['cart_type']]]['discount']),2):0);
                            $item_info[$key][$content_index]['info']['final_price'] = $item_info[$key][$content_index]['info']['final_price'] + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                        }
                        //否则计算套装折扣
                        elseif (isset($content["info"]["discount"])) {
                            $discount=floatval($content["info"]["discount"])==0?1:floatval($content["info"]["discount"]);
                            $item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"])?round(($item["price_base"] + $item["_price_custom"]) * ($discount),2):0);
                            $item_info[$key][$content_index]['info']['final_price'] = $item_info[$key][$content_index]['info']['final_price'] + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                        }
                        else{
                            $item_info[$key][$content_index]["items"][$i]["final_price"] = (intval($item["price_base"])?round(($item["price_base"] * $item["price_discount"] + $item["_price_custom"] * $item["_price_discount"]),2):0);
                            $item_info[$key][$content_index]['info']['final_price'] = $item_info[$key][$content_index]['info']['final_price'] + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                        }
                        //计算全场优惠券用到的原价总和
                        if (!$item_exclude && !empty($coupon_arr['all'])) {
                            $item_info[$key][$content_index]["items"][$i]["final_price"] = intval($item["price_base"])?round($item["price_base"] + $item["_price_custom"]):0;
                            $total_all_price = $total_all_price + $item_info[$key][$content_index]["items"][$i]["final_price"] * $item["count"] * $item_info[$key][$content_index]['info']['count'];
                        }

                        $t_count = $t_count + $item['count'] * $item_info[$key][$content_index]['info']['count'];

                        if (!(isset($content["info"]["exclude"])&&!empty($content["info"]["exclude"])&&in_array($item['item_id'],$content["info"]["exclude"]))) {
                            $item_info[$key][$content_index]['info']['origin_price'] = $item_info[$key][$content_index]['info']['origin_price'] + round(($item["price_base"] + $item["_price_custom"]) * $item["count"],2);
                        }

                    }

                    $total_count = $total_count + $t_count;

                    $tz_total_price = $tz_total_price + $item_info[$key][$content_index]['info']['final_price'];
                    //筛选出最大价格的套装
                    if ($item_info[$key][$content_index]['info']['final_price'] > $max_tz_price) {
                        $max_tz_price = $item_info[$key][$content_index]['info']['final_price'];
                        $max_tz_index = $content_index;
                    }
                    //筛选出最大价格的指定id的套装
                    if (!empty($coupon_arr['set']) && $coupon_arr['set']['action_id']==$content['info']['id']) {
                        if ($item_info[$key][$content_index]['info']['final_price'] > $max_action_tz_price) {
                            $max_action_tz_price = $item_info[$key][$content_index]['info']['final_price'];
                            $max_action_tz_index = $content_index;
                        }
                    }
                }

                //最大价格的指定id的套装计算
                if (!empty($coupon_arr['set']) && $coupon_arr['set']['action_id']==$item_info[$key][$max_action_tz_index]['info']['id']) {

                    $tz_total_price = $tz_total_price - $item_info[$key][$max_action_tz_index]['info']['final_price'];
                    $item_info[$key][$max_action_tz_index]['info']['final_price'] = PrfCoupon::coupon_calc($item_info[$key][$max_action_tz_index]['info']['origin_price'], $item_info[$key][$max_action_tz_index]['info']['count'], $coupon_arr['set']);
                    $tz_total_price = $tz_total_price + $item_info[$key][$content_index]['info']['final_price'];
                    if(!isset($item_info['coupon'])){
                        $item_info['coupon']=[];
                    }
                    $item_info['coupon']['set']=$coupon_arr['set'];
                }

                //最大价格的套装计算
                if (!empty($coupon_arr['set']) && $coupon_arr['set']['action_id']==0) {
                    $tz_total_price = $tz_total_price - $item_info[$key][$max_tz_index]['info']['final_price'];
                    $item_info[$key][$max_tz_index]['info']['final_price'] = PrfCoupon::coupon_calc($item_info[$key][$max_tz_index]['info']['origin_price'], $item_info[$key][$max_tz_index]['info']['count'], $coupon_arr['set']);
                    $tz_total_price = $tz_total_price + $item_info[$key][$max_tz_index]['info']['final_price'];
                    if(!isset($item_info['coupon'])){
                        $item_info['coupon']=[];
                    }
                    $item_info['coupon']['set']=$coupon_arr['set'];
                }
                $total_price = $total_price + $tz_total_price;
            }
        }
        if (!empty($coupon_arr['all'])) {
            $total_price = intval(PrfCoupon::coupon_calc($total_all_price, 1, $coupon_arr['all']));
            $item_info['coupon']['all'] = $coupon_arr['all'];
        }else{
            $total_price = intval($total_price);
        }

        if ($total_price != $post_total_price) {
            echo '计算出错';
            $result = 0;
            return  $this->redirect(Url::to(['account/submit-result', 'result' => $result, 'trade_no' => $trade_no, 'enquiry' => $consolt]));
        }

        //写入数据库
        $payTrade = new PayTrade();
        $payTrade->trade_no = $trade_no;
        $payTrade->user_id = $user_id;
        $payTrade->address = $address;
        $payTrade->message = $message;
        $payTrade->number = $total_count;
        $payTrade->price = $total_price;
        $payTrade->price_modify = $total_price;
        $payTrade->price_state = 0;
        $payTrade->create_time = time();
        $payTrade->modify_time = time();
        $payTrade->trade_state = $consolt;
        $payTrade->audit_state = 0;
        $payTrade->refund_audit = 0;
        $payTrade->content = stripslashes(json_encode($item_info,JSON_UNESCAPED_UNICODE));

        if($payTrade->save())
        {
            $result = 1;
            $t=array(
                "state"=>true,
                "trade_no"=>$trade_no
            );
            UserShoppingCart::deleteCart($cart_id_array);
            if (!empty($item_info['coupon'])) {
                $user_coupon_arr=[];
                foreach ($item_info['coupon'] as $type => $value) {
                    $user_coupon_arr[]=$value['id'];
                }
                PrfCoupon::useCoupon($user_coupon_arr);
            }
        }
        else
        {
            $t=array(
                "state"=>false,
                "trade_no"=>NULL,
                "error"=>$sql
            );
        }
        echo json_encode($t,JSON_UNESCAPED_UNICODE);
        //发信息
        $sms = new SendSms();
        $row = UserInfo::findOne(['id' => $user_id]);
        if ($row["user_from"] == 1) {
            $tel = $row["tel"];
        } else {
            $row = UserAddress::findOne(['id' => $address_id]);
            $tel = $row["mobile"];
        }
        $msg = '我们已经收到您的订单，感谢信任，您可以随时回JAJAHOME App查看订单详情。您可以关注我们的微信公众号“设计拍档”获取最新生活方式资讯，设计严选，缔造美好生活。客服电话：400-690-3766';
        $sms->send_mobile_SMS($tel, $msg);

        return $this->redirect(Url::to(['account/submit-result', 'result' => $result, 'trade_no' => $trade_no, 'enquiry' => $consolt]));

    }

}
